import socket

# 1.编写一个TCP服务端程序
# 创建TCP服务端socket
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置端口号复用，程序退出端口立即释放
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 绑定端口号
tcp_server_socket.bind(('', 80))
# 设置监听
tcp_server_socket.listen(128)
# 循环接收客户端的连接请求
while True:
    # 等待接收客户端的连接请求
    conn_socket, ip_port = tcp_server_socket.accept()
    # 2.获取浏览器发送的HTTP请求报文数据
    client_request_data = conn_socket.recv(4096).decode()
    # 3.读取固定页面数据，把页面数据组装成HTTP响应报文数据发送给浏览器
    with open('static/index.html', 'rb') as f:
        file_data = f.read()
    # 响应行
    response_line = "HTTP/1.1 200 OK\r\n"
    # 响应头
    response_header = "Server: Python Web\r\n"
    # 响应体
    response_body = file_data
    # 组装HTTP格式的响应报文
    response_data = (response_line + response_header + '\r\n').encode() + response_body
    conn_socket.send(response_data)
    # 4.HTTP响应报文数据发送完成后，关闭服务于客户端的套接字
    conn_socket.close()
